package com.gxa.jjty.core.interceptor;

import com.gxa.jjty.core.anno.NeedToken;
import com.gxa.jjty.core.util.StringUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author bill
 * @date 2021/11/11 10:17
 */

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    /**
     * 在方法执行前拦截,做的操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {



        // 把拦截时的操作定义在这里
        System.out.println("PermissionInterceptor preHandle");
        // 返回值表示是否放行, true表示放行 , false表示彻底拦截
        // 先判断是否符合业务逻辑/需求, 符合就返回true, 不符合就返回false
        // 获得前端请求中的header, 得到token
        // 如果token不为""或者null就放行(开发中还需要和session中的token比较)
        HandlerMethod method = (HandlerMethod) handler;
        boolean hasMethodAnnotation = method.hasMethodAnnotation(NeedToken.class);
        if (!hasMethodAnnotation){
            NeedToken needToken = method.getMethodAnnotation(NeedToken.class);
            if (needToken.required()){
                String token = request.getHeader("token");
                if(!StringUtil.isEmpty(token)){
                    HttpSession session = request.getSession();
                    Object sessionToken = session.getAttribute("token");
                    /*if (token.equals(sessionToken)){
                        return true;
                    }else {
                        return false;
                    }*/
                    return true;
                }
                return false;
            }else {
                return true;
            }
        }else {
            return true;
        }

    }

    /**
     * 方法执行后, 放行了, 再执行的操作
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    /**
     * 给jsp渲染时, 生成了数据模型Model后执行的操作
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
